<template>
  <view class="change-password-container">
    <scroll-view scroll-y class="scroll-view">
      <view class="content-area">
        <!-- 表单区域 -->
        <view class="form-section">
          <view class="form-item">
            <view class="form-label">手机号</view>
            <view class="form-input">
              <uv-input
                v-model="formData.mobile"
                placeholder="请输入手机号"
                :border="false"
                :clearable="true"
                :custom-style="inputStyle"
                maxlength="11"
              ></uv-input>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">验证码</view>
            <view class="form-input">
              <uv-input
                v-model="formData.captcha"
                placeholder="请输入验证码"
                :border="false"
                :clearable="true"
                :custom-style="inputStyle"
                maxlength="6"
              ></uv-input>
            </view>
            <view class="captcha-btn" @click="sendCaptcha">
              <text :class="['captcha-text', { disabled: countdown > 0 }]">
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </text>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">新密码</view>
            <view class="form-input">
              <uv-input
                v-model="formData.newpassword"
                type="password"
                placeholder="请输入新密码"
                :border="false"
                :clearable="true"
                :custom-style="inputStyle"
              ></uv-input>
            </view>
          </view>

          <view class="form-item">
            <view class="form-label">确认密码</view>
            <view class="form-input">
              <uv-input
                v-model="formData.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                :border="false"
                :clearable="true"
                :custom-style="inputStyle"
              ></uv-input>
            </view>
          </view>
        </view>

      </view>
    </scroll-view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <uv-button
        type="primary"
        text="确认修改"
        size="large"
        :custom-style="submitButtonStyle"
        @click="submitChangePassword"
      ></uv-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRequest } from '@/api'
const { API_SMS_SEND, API_UPDATE_PWD } = useRequest()
import { UserInfoManager } from '@/utils/userInfo'
import { TokenManager } from '@/utils/token'
// 倒计时
const countdown = ref(0)

// 表单数据
const formData = reactive({
  mobile: '',
  newpassword: '',
  confirmPassword: '',
  captcha: ''
})

// 输入框样式
const inputStyle = {
  backgroundColor: '#f8f9fa',
  borderRadius: '12rpx',
  padding: '12rpx',
  fontSize: '28rpx',
  color: '#333'
}

// 提交按钮样式（参考设置页面）
const submitButtonStyle = {
  backgroundColor: '#FF6B35',
  borderColor: '#FF6B35',
  borderRadius: '24rpx',
  height: '88rpx',
  fontSize: '32rpx',
  fontWeight: '600'
}

// 发送验证码
const sendCaptcha = async () => {
  // 检查是否在倒计时中
  if (countdown.value > 0) {
    return
  }

  // 验证手机号
  if (!formData.mobile.trim()) {
    uni.showToast({ title: '请输入手机号', icon: 'none' })
    return
  }

  // 验证手机号格式
  const mobileRegex = /^1[3-9]\d{9}$/
  if (!mobileRegex.test(formData.mobile)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
    return
  }

  try {
    const params = {
      mobile: formData.mobile,
      event: 'resetpwd' // 验证码类型
    }
    
    const res = await API_SMS_SEND(params)
    if (res.code === 1) {
      uni.showToast({ title: '验证码已发送', icon: 'success' })
      
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    
  }
}

// 验证密码格式
const validatePassword = (password: string) => {
  // 长度8-20位
  if (password.length < 8 || password.length > 20) {
    return false
  }
  // 包含字母和数字
  const hasLetter = /[a-zA-Z]/.test(password)
  const hasNumber = /\d/.test(password)
  return hasLetter && hasNumber
}

// 提交修改密码
const submitChangePassword = async () => {
  // 验证必填字段
  if (!formData.mobile.trim()) {
    uni.showToast({ title: '请输入手机号', icon: 'none' })
    return
  }

  // 验证手机号格式
  const mobileRegex = /^1[3-9]\d{9}$/
  if (!mobileRegex.test(formData.mobile)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
    return
  }

  if (!formData.newpassword.trim()) {
    uni.showToast({ title: '请输入新密码', icon: 'none' })
    return
  }

  if (!formData.confirmPassword.trim()) {
    uni.showToast({ title: '请输入确认密码', icon: 'none' })
    return
  }

  // 验证两次密码输入是否一致
  if (formData.newpassword !== formData.confirmPassword) {
    uni.showToast({ title: '两次输入的密码不一致', icon: 'none' })
    return
  }

  if (!formData.captcha.trim()) {
    uni.showToast({ title: '请输入验证码', icon: 'none' })
    return
  }

 
  // 验证新密码格式
  if (!validatePassword(formData.newpassword)) {
    uni.showToast({ title: '请输入8~20位英文+数字组合的密码', icon: 'none' })
    return
  }

  // 显示提交中状态
  uni.showLoading({ title: '修改中...' })
  
  try {
    const params = {
      mobile: formData.mobile,
      newpassword: formData.newpassword,
      captcha: formData.captcha,
      // isdriver: UserInfoManager.lastrole()
    }
    
    const res = await API_UPDATE_PWD(params)
    if (res.code === 1) {
      uni.hideLoading()
      uni.showToast({ title: '密码修改成功', icon: 'success' })
      
      // 清空 token 和用户信息
      TokenManager.removeToken()
      UserInfoManager.removeUserInfo()
      
      // 延迟跳转到登录页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }, 1500)
    } else {
      uni.hideLoading()
      uni.showToast({ title: res.msg || '修改失败', icon: 'none' })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('修改密码失败:', error)
    uni.showToast({ title: '修改失败', icon: 'none' })
  }
}
</script>

<style lang="scss" scoped>


.content-area {
  padding: 32rpx;
}

// 表单区域
.form-section {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 24rpx;

  .form-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .form-label {
      width: 160rpx;
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }

    .form-input {
      flex: 1;
      margin-left: 24rpx;
    }

    .captcha-btn {
      margin-left: 24rpx;
      padding: 16rpx 24rpx;
      background: #FF6B35;
      border-radius: 8rpx;
      min-width: 160rpx;
      text-align: center;

      .captcha-text {
        font-size: 28rpx;
        color: #fff;
        font-weight: 500;

        &.disabled {
          color: #999;
        }
      }
    }
  }
}


.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 32rpx;
  background: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
}

// 深度样式调整
:deep(.uv-input__input) {
  font-size: 28rpx !important;
  color: #333 !important;
}

:deep(.uv-input__placeholder) {
  color: #999 !important;
  font-size: 28rpx !important;
}
</style>
